<?php
namespace App\Common\Library;


use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use Base\Model;
use EasySwoole\Component\Pool\PoolManager;

final class TransactionService
{
    /**
     * 事务启动方法
     * @param $call
     * @return mixed
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \Throwable
     */
    public function begin($call)
    {
        $db = MysqlPool::defer();;
        if ($db instanceof MysqlObject) {
            if ($db->startTransaction()) {
                try {
                    $res = call_user_func($call, $db);
                    if (!empty($res)) {
                        $db->commit();
                    } else {
                        $db->rollback();
                    }
                    return $res;
                } catch (\Throwable $ex) {
                    $db->rollback();
                    throw $ex;
                } finally {
                    unset($db);
                }
            }
            throw new \Exception('事务开启失败！');
        }
        throw new \Exception('连接对象获取失败！');
    }

}